package lib

import (
	"algorithms/ds"
)

func init() {
	Probs = append(Probs, Problem{
		Num:         2,
		Discription: "两数逆位相加",
		Level:       2,
		Labels: map[string]int{
			"链表": 1,
		},
	})
}

func AddTwoNumbers(l1 *ds.ListNode, l2 *ds.ListNode) *ds.ListNode {
	preHead := &ds.ListNode{}
	cur := preHead
	overflow := 0
	//记得最后单独有仅为的情况
	for l1 != nil || l2 != nil || overflow != 0 {
		val := overflow
		//还得判空防止单独进位
		if l1 != nil || l2 != nil {
			if l1 == nil {
				val += l2.Val
				l2 = l2.Next
			} else if l2 == nil {
				val += l1.Val
				l1 = l1.Next
			} else {
				val += l1.Val + l2.Val
				l2 = l2.Next
				l1 = l1.Next
			}
		}

		overflow = val / 10
		val = val % 10
		cur.Next = &ds.ListNode{
			Val: val,
		}
		cur = cur.Next
	}

	return preHead.Next
}
